package com.disney.dolcn.invitemail.util;

import java.util.Properties;
import javax.mail.Authenticator;
import javax.mail.BodyPart;
import javax.mail.Message;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import org.apache.log4j.Logger;

/**
 * 
 * @author hawang
 * 
 */
public class MailService {
	private static Logger logger = Logger.getLogger(MailService.class);
	public String mailServer;
	public String fromMail;
	public String userName = "";
	public String passWord = "";

	/**
	 * 
	 * @param mailserver
	 * @param frommail
	 * @param username
	 * @param password
	 */
	public MailService(String mailserver, String frommail, String username,
			String password) {
		this.mailServer = mailserver;
		this.fromMail = frommail;
		this.userName = username;
		this.passWord = password;
	}

	/**
	 * send mail
	 * 
	 * @param toMail
	 * @param subject
	 * @param content
	 * @return
	 */
	public boolean sendMail(String toMail, String subject, String content,
			String from) throws Exception {
		boolean tag = false;
		 
			Authenticator auth = new PopupAuthenticator(userName, passWord);
			Properties mailProps = new Properties();
			mailProps.put("mail.smtp.host", mailServer);
			mailProps.put("mail.smtp.auth", "true");
			mailProps.put("username", userName);
			mailProps.put("password", passWord);

			Session mailSession = Session.getInstance(mailProps, auth);
			MimeMessage message = new MimeMessage(mailSession);
			InternetAddress internetAddress = new InternetAddress(fromMail);
			internetAddress.setPersonal(from);
			message.setFrom(internetAddress);
			message.setRecipient(Message.RecipientType.TO, new InternetAddress(
					toMail));
			message.setSubject(subject);
			MimeMultipart multi = new MimeMultipart();
			BodyPart textBodyPart = new MimeBodyPart();
			textBodyPart
					.setContent(content.toString(), "text/html;charset=GBK");
			multi.setSubType("related");
			multi.addBodyPart(textBodyPart);
			message.setContent(multi);
			message.saveChanges();
			Transport.send(message);
			tag = true;
			logger.info("send mail is okk");
		 System.out.println(toMail+":"+subject+":"+content);
		return tag;
	}
}

/**
 * 
 * @author hawang
 * 
 */
class PopupAuthenticator extends Authenticator {
	String username = "";
	String pwd = "";

	/**
	 * 
	 * @param username
	 * @param pwd
	 */
	public PopupAuthenticator(String username, String pwd) {
		this.username = username;
		this.pwd = pwd;
	}

	/**
	 * 
	 * @return
	 */
	public PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(username, pwd);
	}
}
